<?php

namespace App\Http\Controllers\Admin\Ad;

use App\Models\Ad\Advert;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;

class AdvertController extends Controller
{
   /**
    * Display a listing of the resource.
    *
    * @return \Illuminate\Http\Response
    */
   public function index(Request $request)
   {
      $where = function ($query) use ($request) {
         if ($request->has('keyword') and $request->keyword != '') {
            $cate = $request->cate;
            $search = "%" . $request->keyword . "%";
            $query->where('a.' . $cate, 'like', $search);
         }

         if ($request->has('category_id') and $request->category_id != '') {
            $query->where('category_id', $request->category_id);
         }
      };

      $adverts = DB::table('adverts as a')
         ->join('advert_nodes as b', 'a.category_id', '=', 'b.id')
         ->select('a.*', 'b.name as cate_name')
         ->where($where)
         ->orderByDesc('a.sort_order')
         ->orderByDesc('created_at')
         ->paginate(config('admin.page_size'));

      return response()->json($adverts);
   }

   /**
    * Store a newly created resource in storage.
    *
    * @param \Illuminate\Http\Request $request
    * @return \Illuminate\Http\Response
    */
   public function store(Request $request)
   {
      $advert = Advert::create($request->all());
      if ($advert) {
         $info = ['status' => 1, 'msg' => '新增广告成功~'];
         return response()->json($info);
      }
   }

   /**
    * Display the specified resource.
    *
    * @param int $id
    * @return \Illuminate\Http\Response
    */
   public function show($id)
   {
      $advert = Advert::find($id);
      return response()->json($advert);
   }

   /**
    * Update the specified resource in storage.
    *
    * @param \Illuminate\Http\Request $request
    * @param int $id
    * @return \Illuminate\Http\Response
    */
   public function update(Request $request, $id)
   {
      $advert = Advert::find($id);
      $advert->update($request->all());
   }

   /**
    * Remove the specified resource from storage.
    *
    * @param int $id
    * @return \Illuminate\Http\Response
    */
   public function destroy($id)
   {
      Advert::destroy($id);
   }

   /***
    *  改变属性
    */
   public function change_attr(Request $request)
   {
      $advert = Advert::find($request->id);
      $attr = $request->attr;
      $advert->$attr = $advert->$attr ? false : true;
      $advert->save();
   }

   /***
    * 排序
    */
   public function change_sort(Request $request)
   {
      $advert = Advert::find($request->id);
      $advert->sort_order = $request->sort_order;
      $advert->save();
   }

   /***
    * 多选删除
    */
   public function delete_all(Request $request)
   {
      Advert::destroy($request->checked_id);
   }
}
